$(document).ready(function(){
	drag();
	formInfoSwitch();

//	$(".col").children("div").find("a.set").trigger("click");
})
function drag(){
	var coreVar = "UIdrag"; 
	var $root = $("*["+coreVar+"]");
	$root.each(function(){
		var $this=$(this),
			cXY=new Array(),																			//创建坐标数组
			$col=$this.children(".col"),																//获取所有列
			$dragBox=$col.children(".dragBox"),															//获取所有可拖动模块
			$lastBox=$('<div class="dragBox last"></div>');												//生成每列最后一个空模块
		$this.css({"position":"relative"});															//获取控件最外层，并为其加入定位模式
		$col.append($lastBox);
		
		coordinate();
		mouseXY();
		function closeDrag(){
			var $box=$col.children("div");
			$box.each(function(){
				var $this=$(this);
				$this.find(".close").unbind("click").click(function(){
					$this.remove();
					coordinate();
				})
			})
		}
		//拖动模块定位
		function mouseXY(){
			var tempBoxSwitch=0;
			$dragBox.each(function(){
				var $thisDrag=$(this);
				var $moveBar=$thisDrag.find(".movebar");
				var $ctrlBar=$thisDrag.children("a");
				var $addBox=$this.find(".addBox");
				/*$thisDrag.hover(
					function(){
						if(!$thisDrag.hasClass("dragEdit")){
							$moveBar.show();
							$ctrlBar.show();
						}
					},
					function(){
						$moveBar.hide();
						$ctrlBar.hide();
					}
				)*/
				$moveBar
				//.css({"width":parseInt($thisDrag.outerWidth())-parseInt($moveBar.css("border-left-width"))*2,"height":parseInt($thisDrag.outerHeight())-parseInt($moveBar.css("border-top-width"))*2})
				.mousedown(function(ev){
					var oEvent 		= ev || event,														//鼠标事件
						dragPos		= $thisDrag.position(),												//【拖动模块】距【控件最外层】定位
						rootOffset	= $this.offset(),													//【控件最外层】距【页面】定位
						scrollLeft	= document.documentElement.scrollLeft+document.body.scrollLeft,		//屏幕卷去宽度
						scrollTop	= document.documentElement.scrollTop+document.body.scrollTop,		//屏幕卷去高度
						thisW		= $thisDrag.outerWidth(),											//【拖动模块】的宽度
						thisH		= $thisDrag.outerHeight(),											//【拖动模块】的高度
						tempBox		= $('<div class="tempBox" style="height:'+thisH+'px"><div class="tempInner"></div></div>'),		//生成临时占位模块
						dragX		= oEvent.clientX - rootOffset.left - dragPos.left + scrollLeft,		//获取鼠标与【拖动模块】左边的距离
						dragY		= oEvent.clientY - rootOffset.top - dragPos.top + scrollTop,		//获取鼠标与【拖动模块】头部的距离
						$thisCol	= $thisDrag.parents(".col"),										//获取当前模块所在的列
						areaL		= $thisCol.position().left+parseInt($thisCol.css("marginLeft")),	//【当前列左侧坐标】距【控件最外层】左侧坐标
						areaR		= areaL+$thisCol.outerWidth();										//【当前列右侧坐标】距【控件最外层】左侧坐标
					
					$('<div class="visible" style="display:none; "></div>').appendTo($this).append($addBox);//隐藏【添加按钮】
					
					document.onmousemove = function(ev){
						
						//模块拖动效果
						var oEvent = ev||event,															//鼠标事件
							Left,																		//【拖动模块】距【控件最外层】左部距离
							Top,																		//【拖动模块】距【控件最外层】顶部距离
							posLeft	= oEvent.clientX-rootOffset.left,									//鼠标距【控件最外层】左部距离
							posTop;																		//鼠标距【控件最外层】顶部距离
						
						if(scrollTop == 0){
							Left = oEvent.clientX - rootOffset.left - dragX ;
							Top = oEvent.clientY - rootOffset.top  - dragY;
						}else{
							Left = oEvent.clientX - rootOffset.left - dragX + scrollLeft;
							Top = oEvent.clientY - rootOffset.top  - dragY + scrollTop;
						}
						
						if(typeof($thisDrag.attr("dragMode"))!="undefined"){
							if(Left<areaL){
								Left=areaL;
								posLeft=areaL;
							}
							if(Left+$thisCol.outerWidth()>areaR){
								Left=areaR-$thisCol.outerWidth();
								posLeft=areaR-$thisCol.outerWidth();
							}
						}
						
						if(tempBoxSwitch==0){
							$thisDrag.after(tempBox).prependTo($this).addClass("floatBox");
							coordinate();
							//$(".qwer").html(cXY)
							tempBoxSwitch=1;
						}
						$thisDrag.css({"left":Left,"top":Top,"height":thisH,"width":thisW});
						
						//模块定位处理
						posTop = dragY + Top;														//鼠标距【控件最外层】顶部距离
						for(a=0; a<cXY.length; a++){
							for(b=0; b<cXY[a].length; b++){
								if((posLeft>cXY[a][b][0] && posLeft<cXY[a][b][1]) && (posTop>cXY[a][b][2] && posTop<cXY[a][b][3]-(cXY[a][b][3]-cXY[a][b][2])/2)){
									$(".tempBox").remove();
									$col.eq(a).children(".dragBox").eq(b).before(tempBox);
									coordinate();
									//$(".qwer").html(cXY)
								}else if((posLeft>cXY[a][b][0] && posLeft<cXY[a][b][1]) && (posTop>cXY[a][b][2]+(cXY[a][b][3]-cXY[a][b][2])/2 && posTop<cXY[a][b][3])){
									$(".tempBox").remove();
									$col.eq(a).children(".dragBox").eq(b).after(tempBox);
									coordinate();
									//$(".qwer").html(cXY)
								}
							}
						}
					}
					document.onmouseup = function(){
						document.onmousemove = null;
						document.onmouseup = null;
						tempBoxSwitch=0;
						$thisDrag.insertAfter(".tempBox").removeClass("floatBox").removeAttr("style");
						$(".tempBox").remove();
						//$moveBar.css({"width":parseInt($thisDrag.outerWidth())-parseInt($moveBar.css("border-left-width"))*2,"height":parseInt($thisDrag.outerHeight())-parseInt($moveBar.css("border-top-width"))*2});
						$(".last").remove();
						$col.append($lastBox);
						coordinate();
						$addBox.each(function(a){
							$addBox.eq(a).appendTo($col.eq(a));
						});
						$(".visible").remove();
						closeDrag();
						//$(".qwer").html(cXY)
//						alert(cXY)
						savePage();
					};
					return false;
				})
				$($thisDrag.find("img")).load(function(){
					//$moveBar.css({"width":parseInt($thisDrag.outerWidth())-parseInt($moveBar.css("border-left-width"))*2,"height":parseInt($thisDrag.outerHeight())-parseInt($moveBar.css("border-top-width"))*2})
				});
			})
		}
		
		//获取所有可拖动元素的坐标
		function coordinate(){
			$col.each(function(n){
				var $thisDragCol=$(this),					//当前列
					colPos=$thisDragCol.position();			//当前列定位
				var $row=$thisDragCol.children(".dragBox");	//当前列里的所有模块
				$thisDragCol.find(".last").css({"height":$thisDragCol.height()+1000})
				
				cXY[n]=new Array();
				$row.each(function(m){
					var $thisDragRow=$(this),				//当前模块
						rowPos=$thisDragRow.position();		//当前模块定位
					cXY[n][m]=new Array();
					cXY[n][m][0]=colPos.left;
					cXY[n][m][1]=colPos.left+$thisDragCol.width();
					cXY[n][m][2]=rowPos.top;
					cXY[n][m][3]=rowPos.top+$thisDragRow.height();
				})
			})
			$(".last").removeAttr("style").css({height:0,opacity:0});
			closeDrag();
		}
	})
}


//全局设置对话框
function globalDialog(dialog,closeDialog,init){
	
	//获取初始数据
	dialog.find("#headH .hInput").html(parseInt(init.headH));
	dialog.find("#h1Size").val(parseInt(init.h1Size));
	dialog.find("#h1Color").val(init.h1Color);
	dialog.find("#dragTitleSize").val(parseInt(init.dragTitleSize));
	dialog.find("#dragTitleColor").val(init.dragTitleColor);

	if($(".template").children("div").first().hasClass("template_headBg")){
		dialog.find(".navPos input:checkbox").removeAttr("checked");
	}else{
		dialog.find(".navPos input:checkbox").attr("checked","true");
	}
	dialog.find(".navPos input:checkbox")
	var presentVal=parseInt(init.headH),
		minVal=150,
		maxVal=400,
		coreVar = "UIdragAdjust", 
		$root = $("*["+coreVar+"]");
	$root.each(function(){
		var $this=$(this),
			$headHbar=$this.find(".hBar"),
			$headHline=$this.find(".hLine"),
			$headHinput=$this.find(".hInput"),
			Left=(presentVal-minVal)/(maxVal-minVal)*$this.width()-$headHbar.width();
			
		$headHbar.css({"left":Left});
		adjustVal=parseInt((Left+$headHbar.width())/$this.width()*(maxVal-minVal)+minVal);
		$headHinput.html(adjustVal);
		
		$headHbar.mousedown(function(ev){
			var oEvent = ev || event;
			var dragX = oEvent.clientX - $this.offset().left-$headHbar.position().left;
			dialog.css({"opacity":0.2});
			$headHbar.css({"backgroundColor":"#000"});
			document.onmousemove = function(ev){
				var oEvent = ev || event;
				Left = oEvent.clientX - $this.offset().left - dragX;
				if (Left<0){
					Left=0;
				}
				if(Left>$this.width()-$headHbar.width()){
					Left = $this.width()-$headHbar.width();
				}
				adjustVal=parseInt((Left+$headHbar.width())/$this.width()*(maxVal-minVal)+minVal);
				if(Left==0){
					adjustVal=minVal;
				}
				$headHbar.css({"left":Left});
				$headHinput.html(adjustVal);
				$(".template_headBg").height(adjustVal);
				$(".template_headBg .template_head").height(adjustVal);
				
			}
			document.onmouseup = function(){
				document.onmousemove = null;
				document.onmouseup = null;
				dialog.css({"opacity":1});
				$headHbar.css({"backgroundColor":""});
			};
		})
		//console.log($(this).parent());
		return false;
			
	})
	//点击保存按钮
	dialog.find(".dialogSave a.saveBtn").unbind("click").click(function(){
		init.headH=$("#headH .hInput").html();
		init.h1Size=$("#h1Size").val();
		init.h1Color=$("#h1Color").val();
		init.dragTitleSize=$("#dragTitleSize").val();
		init.dragTitleColor=$("#dragTitleColor").val();
		$(".template_headBg").height(init.headH);
		$(".template_headInner h1").css({"fontSize":parseInt(init.h1Size),"color":init.h1Color});
		$(".col>div .title").css({"fontSize":parseInt(init.dragTitleSize),"color":init.dragTitleColor});
		if(dialog.find(".navPos input:checkbox").is(":not(:checked)")){
			$(".template_headBg").prependTo(".template").removeClass("template_headBgLower");
			$(".template_headNav").removeClass("template_headNavUpper");
			$(".template_headInner").removeClass("template_headInnerLower");
		}else{
			$(".template_headNav").prependTo(".template").addClass("template_headNavUpper");
			$(".template_headBg").addClass("template_headBgLower");
			$(".template_headInner").addClass("template_headInnerLower");
		}
		closeDialog();
	})
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		$(".template_headBg").height(presentVal);
		$(".template_headBg .template_head").height(presentVal);
		closeDialog();
	})
}

//头部图片设置对话框
function headPicDialog(dialog,closeDialog){
	UIslide();//滑动
	UIchoose();//选择
	
	//点击保存按钮
	dialog.find(".dialogSave a").unbind("click").click(function(){
		closeDialog();
	})
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		closeDialog();
	})
}

//导航设置对话框
function navDialog(dialog,closeDialog){
	//结构初始化
	var $navLi=$(".template_headNav li a:not(.add)");
	var $tbody=$("#nav tbody");
	var $tr=$('<tr width="100%" class="dragBox"><td width="60" class="movebar"></td><td width="160"><input type="text" class="input" /></td><td width="160"></td><td width="160"><input type="checkbox" class="checkbox" /><span class="text">启用</span></td><td width="160"><input type="checkbox" class="checkbox" /><span class="text">同首页</span></td><td width="100"><a href="#" class="lBtn sBtn sBtnDel">删除</a></td></tr>')
	for(i=0;i<$navLi.length;i++){
		$tbody.append($tr.clone());
	}
	$tbody/*.find("tr:eq(0)").removeClass("dragBox")*/.parents("table").attr({"UIdrag":"UIdrag"});
	drag();
	//获取初始数据
	$tbody.find("tr").each(function(n){
		var $thisTr=$(this);
		$thisTr.attr({"navLink":$navLi.eq(n).attr("href"),"navChoose":$navLi.eq(n).attr("class")});
		$thisTr.find("td:eq(1)>input").val($navLi.eq(n).html());
		$thisTr.find("td:eq(2)").html($navLi.eq(n).attr("pageName"));
		$tbody.find("td:contains('首页')+td>input:checkbox").attr({"disabled":"disabled"});
		if($navLi.eq(n).is(":not(:hidden)")){
			$thisTr.find("td:eq(3)>input:checkbox").attr("checked","true");
		}else{
			$thisTr.find("td:eq(3)>input:checkbox").removeAttr("checked");
		}
		$thisTr.find("td:eq(4)>span").each(function(){
			$(this).unbind("click").click(function(){
				$thisTr.find("td:eq(4)>span").removeClass("choose");
				$(this).addClass("choose");
			})
		})
	})
	//点击保存按钮
	dialog.find(".dialogSave a").unbind("click").click(function(){
		$navLi.removeAttr("class");
		$tbody.find("tr").each(function(n){
			var $thisTr=$(this);
			$navLi.eq(n).attr({"href":$thisTr.attr("navLink"),"class":$thisTr.attr("navChoose")});
			$navLi.eq(n).html($thisTr.find("td:eq(1)>input").val());
			$navLi.eq(n).attr({"pageName":$thisTr.find("td:eq(2)").html()});
			if($thisTr.find("td:eq(3)>input:checkbox").is(":not(:checked)")){
				$navLi.eq(n).parent("li").hide();
			}else{
				$navLi.eq(n).parent("li").show();
			}
		})
		$tbody.empty();
		closeDialog();
	});
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		$tbody.empty();
		closeDialog();
	})
}

//添加模块对话框
function addModuleDialog(dialog,closeDialog,init,thisBtn,initAdd,info){
	dialog.find("li").show();
	//在列表中删除页面里已存在模块
	var $module=$("[dragID]");										//找到页面中已存在的模块
	$module.each(function(){
		var $this=$(this);											//当前模块
			thisDragID=$this.attr("dragID");						//获取当前模块ID
			$thisModule=dialog.find("li[moduleID="+thisDragID+"]");	//匹配对话框中模块ID
		if(typeof($thisModule.attr("moduleRepeat"))=="undefined"){	//判断当前模块是否可重复添加
			$thisModule.hide();									//不可重复添加则删除
		}
	})
	var category=thisBtn.attr("boxW");
	var $outside=dialog.find("li:not(."+category+")");
	$outside.each(function(){
		$(this).hide();									//不可重复添加则删除
	})
	//对话框中模块列表点击效果
	var $moduleLi=dialog.find("li:visible");
	dialog.find(".save").hide();
	$moduleLi.each(function(){
		var $this=$(this);
		var classArray=$this.attr("class").split(" ");
		if(classArray.length == 1){
			$this.attr({"dragMode":"col"});
		}
		$this
		.hover(
			function(){$this.addClass("hover");},
			function(){$moduleLi.removeClass("hover");}
		)
		.click(function(){
			$moduleLi.removeClass("choose");
			$this.addClass("choose");
//			dialog.find(".dialogSave a").trigger("click");
		})
	})
	//点击保存按钮
	dialog.find(".dialogSave a").unbind("click").click(function(){
		var $moduleLiChoose=dialog.find("li.choose");
		if($moduleLiChoose.length != 0){
			var moduleID=$moduleLiChoose.attr("moduleID");
			if(moduleID!="image"&&moduleID!="video"&&$("[data-module='"+moduleID+"']:visible").size()>0){
				alert("不能重复添加此模块");
				return false;
			}
			var $newBox = $("[data-module='"+moduleID+"']").eq(0).clone();
//			alert(moduleID);
			var $addBox=thisBtn.parent(".addBox");
			$addBox.before($newBox).parents(".col").find(".last").remove();
//			var $newBox=$('<div class="dragBox"><div class="ctrl movebar"><a href="javascript:void(0);" class="close"></a><a href="javascript:void(0);" class="set"></a></div><div class="title">'+$moduleLiChoose.find(".name").html()+'</div><div class="innerBox"></div></div>');
			var $addBox=thisBtn.parent(".addBox");
			if(typeof($moduleLiChoose.attr("noset"))!="undefined"){
				$newBox.find("a.set").remove();
			}
			if(typeof($moduleLiChoose.attr("dragMode"))!="undefined"){
				$newBox.attr({"dragMode":"col"});
			}
			$addBox.before($newBox).parents(".col").find(".last").remove();
			$addBox.prev(".dragBox").attr({"dragID":moduleID}).find(".innerBox").load("module.html #"+moduleID+" .form",function(){
				$addBox.prev(".dragBox").find(".titleInfo").val($addBox.prev(".dragBox").find(".title").html());
				formInfoSwitch();
				$addBox.prev(".dragBox").find("a.set").trigger("click");
				
			});
			$addBox.prev(".dragBox").find(".title").css({"fontSize":parseInt(init.dragTitleSize),"color":init.dragTitleColor});
			drag();
			$moduleLi.removeClass("choose");
		}
		closeDialog();
	})
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		$moduleLi.removeClass("choose");
		closeDialog();
	})
}

function formInfoSwitch(){//编辑与保存切换
	var $module=$(".col").children("div");
	$module.each(function(){
		var $this=$(this);
		var moduleID=$this.attr("dragID");
		var $save;
		$this.find("a.set").unbind("click").click(function(){
			if($this.find(".form").length==0){
				$this.find(".innerBox").load("module.html #"+moduleID+" .form",function(){
					if($this.find(".title").is(":visible")){
						$this.find(".titleShow").attr("checked","true")
					}else{
						$this.find(".titleShow").removeAttr("checked");
					}
					$this.find(".titleInfo").val($this.find(".title").html());
					save();
				});
			}else{
				save();
			}
			function save(){
				$save=$this.find(".saveBox a");
				$save.unbind("click").click(function(){
					if($this.find(".titleInfo").val()!=""){
						$this.find(".title").html($this.find(".titleInfo").val());
					}
					if($this.find(".titleShow:checkbox").is(":checked")){
						$this.find(".title").show();
					}else{
						$this.find(".title").hide();
					}
					$this.find(".innerBox").load("module.html #"+moduleID+" .info",function(){
						if($this.find("[UIselect]").length!=0){
							UIselect();
						}
					});
				})
			}
		});
	});
	
}
//选择
function UIchoose(){
	var coreVar = "choose"; 
	var $root = $("*["+coreVar+"]");
	$root.each(function(index){
		var $switcher = $(this).find("li");
		var $choose = $('<div class="icon"></div><div class="clear"></div>');
		$switcher.each(function(){
			var $this=$(this);
			$this.click(function(){
				$switcher.removeClass("choose").find("a").siblings().remove();
				$this.prepend($choose).addClass("choose");
				return false;
			})
		})
	})
}

function createPageDialog(dialog,closeDialog,init,thisBtn,initAdd,info){
	//点击保存按钮
	dialog.find(".dialogSave a").unbind("click").click(function(){
		closeDialog();
	})
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		closeDialog();
	})
}

function detailDialog(dialog,closeDialog,init,thisBtn,initAdd,info){
	//点击保存按钮
	//dialog.find(".dialogSave a").unbind("click").click(function(){
	//	closeDialog();
	//});
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		closeDialog();
	})
}

//创建相册
function createAlbumDialog(dialog,closeDialog,init,thisBtn,initAdd,info){
	//点击保存按钮
	dialog.find(".dialogSave a").unbind("click").click(function(){
		closeDialog();
	})
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		closeDialog();
	})
}

//创建相册
function createAlbumDialog(dialog,closeDialog,init,thisBtn,initAdd,info){
	//点击保存按钮
	dialog.find(".dialogSave a").unbind("click").click(function(){
		closeDialog();
	})
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		closeDialog();
	})
}

//上传照片
function uploadPhotoDialog(dialog,closeDialog,init,thisBtn,initAdd,info){
	//点击保存按钮
	dialog.find(".dialogSave a:eq(0)").unbind("click").click(function(){
		closeDialog();
	})
	
	//点击关闭按钮
	dialog.find(".dialogClose").unbind("click").click(function(){
		closeDialog();
	})
}

